<?php

class Folder implements iFolder {
	
	private
		$path = false,
		$basename = false,
		$dirName = false,
		$list = false,
		$aFiles = false;
	
	public function __construct($path) {
		$this->path = rtrim($path, '/');
		
		if (file_exists($path) && is_dir($path)) {
			$this->basename = basename($path);
			$this->dirName = dirname($path);
		}
	}
	
	public function getPath() {
		return $this->path;
	}
	
	public function getBasename() {
		return $this->basename;
	}
	
	public function getDirName() {
		return $this->dirName;
	}
	
	public function getFiles() {
		if ($this->aFiles) {
			return $this->aFiles;
		}
		
		if (!$this->list) {
			$this->list = scandir($this->path);
		}
		
		$aDirs = array();
		$aFiles = array();
		
		foreach ($this->list as $item) {
			if ($item != '.' && $item != '..') {
				$path = $this->path . '/' . $item;
				
				if (is_dir($path)) {
					$aDirs[] = FilesController::getFile($path);
				} else {
					$aFiles[] = FilesController::getFile($path);
				}
			}
		}
		
		$this->aFiles = array_merge($aDirs, $aFiles);
		
		return $this->aFiles;
	}
	
	public function getListItems() {
		if (!$this->list) {
			return $this->list = scandir($this->path);
		}
	}
	
	public function delete() {
		$aFiles = $this->getFiles();
		
		foreach ($aFiles as $oFile) {
			$oFile->delete();
		}
		
		return rmdir($this->path);
	}
	
	public function __toXML (DOMDocument $xml) {
		$dirNode = $xml->createElement('folder');
		
		$relPath = trim(substr($this->getPath(), mb_strlen(DOC_ROOT)), '/');
		$dirParts = explode('/', $relPath);
		
		$dirNode->setAttribute('path', iconv('CP1251', 'UTF-8//TRANSLIT', $relPath));
		$dirNode->setAttribute('parent', iconv('CP1251', 'UTF-8//TRANSLIT', implode('/', array_slice($dirParts, 0, count($dirParts)-1))));
		$dirNode->setAttribute('name', iconv('CP1251', 'UTF-8//TRANSLIT', $this->getBasename()));
		
		$aFiles = $this->getFiles();
		
		foreach ($aFiles as $oFile) {
			$dirNode->appendChild($oFile->__toXML($xml));
		}
		
		return $dirNode;
	}
		
}